/*
 * =====================================================================================
 *
 *       Filename:  adc.c
 *
 *    Description:  A/D???????(??ADC1)
 *
 * =====================================================================================
 */

#include "stm32f10x.h"
#include "temp.h"

 /*
  * ADC1???,????????,????????????????
  */
void ADC_Config(uint8_t nChannel)
{
    ADC_InitTypeDef  ADC_InitStructure;

    RCC_ADCCLKConfig(RCC_CFGR_ADCPRE_DIV6);//ADC??PLCK2?6?? 12M?ADC????????14M!
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);

    ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;//???????
    ADC_InitStructure.ADC_ScanConvMode = ENABLE; //????
    ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;//ADC?????????
    ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;//???????
    ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;//???????
    ADC_InitStructure.ADC_NbrOfChannel = nChannel;

    ADC_Init(ADC1, &ADC_InitStructure); //???ADC
}

void ADC_Channel_Config(GPIO_TypeDef* GPIOx, uint16_t pin, uint8_t channel, uint8_t rank)
{
    GPIO_InitTypeDef GPIO_InitStructure;

    //  RCC_GPIOClockCmd(GPIOx, ENABLE);  //GPIO??
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);

    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

    GPIO_InitStructure.GPIO_Pin = pin;

    GPIO_Init(GPIOx, &GPIO_InitStructure);

    ADC_RegularChannelConfig(ADC1, channel, rank, ADC_SampleTime_71Cycles5);
}

void ADC_Start()
{
    ADC_Cmd(ADC1, ENABLE);//??ADC1

    ADC_ResetCalibration(ADC1); //??ADC1?????
    while (ADC_GetResetCalibrationStatus(ADC1));//??ADC1??????
    ADC_StartCalibration(ADC1);//??ADC1??
    while (ADC_GetCalibrationStatus(ADC1));//??ADC1????

    ADC_SoftwareStartConvCmd(ADC1, ENABLE); //??ADC1??????
}

/*
 * ???????????,????,??-1
 */
int16_t ADC_Read_Value()
{
    int16_t adc = -1;
    if (ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == SET)
    {
        adc = ADC_GetConversionValue(ADC1);
    }
    return adc;
}
